package org.simpatia.service.rest;

import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
import org.simpatia.Context;
import org.simpatia.Module;
import org.simpatia.Service;

import java.util.HashMap;
import java.util.Map;

public class RESTExportingService implements Service<RESTServiceConfiguration, Void> {

    private TJWSEmbeddedJaxrsServer tjws;
    private RESTServiceConfiguration configuration;
    private Map<String, Object> services;
    private boolean activated;

    public synchronized void activate(String name, RESTServiceConfiguration configuration, Context context) {
        if(activated) {
            throw new RuntimeException("Service is already activated");
        }

        services = new HashMap<String, Object>();
        this.configuration = configuration;
        restartTJWS();

        activated = true;
    }

    public synchronized void destroy() {
        if(activated && tjws != null) {
            tjws.stop();
        }
        services = null;
        activated = false;
    }

    public Void getRESTInterface() {
        return null;
    }

    public void registerService(String serviceName, Module module) {
        if(!activated) {
            throw new RuntimeException("Service is not activated.");
        }

        if(module.getInstance().getRESTInterface() != null) {
            services.put(serviceName, module.getInstance().getRESTInterface()) ;
            tjws.getDeployment().getRegistry().addSingletonResource(module.getInstance().getRESTInterface(), serviceName);
        }
    }

    public void unregisterService(String serviceName) {
        Object service = services.remove(serviceName);

        if(service != null) {
            tjws.getDeployment().getRegistry().removeRegistrations(service.getClass(), serviceName);
        }
    }

    private void restartTJWS() {

        if(tjws != null) {
            tjws.stop();
        }

        tjws = new TJWSEmbeddedJaxrsServer();
        int port = 8080;
        if(configuration != null) {
            port = configuration.getPort();
        }
        tjws.setPort(port);

        tjws.start();
    }
}
